#ifndef _DynamicIB_H_
#define _DynamicIB_H_

template <class Type> class DynamicIB 
{
  private :

		D3DIndexBuffer*	m_pIB;
    uint32 m_Count;
    int m_nOffs;
    Type* m_pLockedData;
    int m_bLocked;
    int m_bReadWrite;










  public :

    uint32 GetCount() const 
    { 
      return m_Count; 
    }
    int GetOffset() const 
    { 
      return m_nOffs; 
    }
    void Reset()
    {
      m_nOffs = 0;
    }
    D3DIndexBuffer* GetInterface() { return m_pIB; }

    DynamicIB()
    {
      m_pIB = 0;

      m_bLocked = false;
      m_bReadWrite = false;
      m_pLockedData = NULL;
      m_nOffs = 0;
      m_Count = 0;






    }

    DynamicIB(D3DDevice *pD3D, const uint32 theElementsCount, bool bReadWrite)
    {
      m_pIB = 0;

      m_bLocked = false;
      m_bReadWrite = bReadWrite;
      m_pLockedData = NULL;
      m_nOffs = 0;







      m_Count = theElementsCount;

      if (m_Count)
        CreateIB(pD3D, m_Count);
    }
    
    HRESULT CreateIB(D3DDevice *pD3D, uint32 theElementsCount)
    {
      m_Count = theElementsCount;

      HRESULT hr = S_OK;
			int32 nUsage; 
			nUsage = CDeviceManager::USAGE_CPU_WRITE;
			nUsage |= ((CDeviceManager::USAGE_CPU_READ|CDeviceManager::USAGE_STAGING) & -m_bReadWrite) | ((CDeviceManager::USAGE_DYNAMIC) & ~m_bReadWrite);
			hr = gRenDev->m_DevMan.CreateBuffer(
				theElementsCount, sizeof(Type), nUsage, CDeviceManager::BIND_INDEX_BUFFER, (D3DBuffer**)&m_pIB);

      assert((hr == S_OK) && (m_pIB));
			






      return hr;
    }

    Type* LockIB(const uint32& theLockCount, uint32 &nOffs, bool bWrite=true, bool bNonStalling=false);

    void UnlockIB();
    void DiscardIB();
    HRESULT Bind();

    int GetSize()
    {
      return _IndexBufferSize(m_pIB);
    }


    void Release()
    {
      UnlockIB();







      SAFE_RELEASE(m_pIB);
    }

    ~DynamicIB()
    {
      Release();
    }
  
};

#endif  _DynamicIB_H_
